<template>
  <div>
    <MyTable :list="list">
      <template #header>
        <th>#</th>
        <th>商品名称</th>
        <th>价格</th>
        <th>标签</th>
        <th>操作</th>
      </template>
      <template #shopping="{ item: item, index: index }">
        <td>{{ item.id }}</td>
        <td>{{ item.goods_name }}</td>
        <td>{{ item.goods_price }}</td>
        <td>
          <keep-alive>
            <input
              class="tag-input form-control"
              type="text"
              v-if="item.inputVisible"
              v-model="item.inputValue"
              v-focus
              @blur="item.inputVisible = false"
              @keyup.enter="addFn(item)"
              @keyup.esc="item.inputValue = ''"
            />
            <button
              class="btn btn-primary btn-sm add-tag"
              v-else
              @click="item.inputVisible = true"
            >
              +Tag
            </button>
          </keep-alive>
          <span
            v-for="(val, index) in item.tags"
            :key="index"
            class="badge badge-warning"
            >{{ val }}</span
          >
        </td>
        <td>
          <button class="btn btn-danger btn-sm" @click="list.splice(index, 1)">
            删除
          </button>
        </td>
      </template>
    </MyTable>
  </div>
</template>

<script>
import MyTable from "../components/MyTable";
export default {
  components: {
    MyTable,
  },
  data() {
    return {
      list: [],
    };
  },
  async created() {
    const res = await this.$http({
      url: "api/goods",
    });
    this.list = res.data.data;
  },
  methods: {
    addFn(item) {
      if (item.inputValue.trim().length == 0) {
        alert("请输入正确内容");
        item.inputVisible = true;
      } else {
        item.tags.push(item.inputValue);
        item.inputValue = "";
        item.inputVisible = false;
      }
      // item.inputValue.trim().length == 0
      //   ? alert("请输入正确内容")
      //   : item.tags.push(item.inputValue);
    },
  },
};
</script>

<style scoped>
.badge {
  margin: 0 5px;
}
.tag-input {
  width: 160px;
}
</style>